import websocket
import threading
import json

class Service:

    def __init__(self, framework):
        self._framework = framework
        self.service = None
        self.service_status = False
        self.service_task = threading.Thread(name="service_task", target=self.task)
        self.service_task.daemon = True
        self.service_task.start()
    
    # 消息服务任务
    def task(self):
        websocket.enableTrace(False)
        self.service = websocket.WebSocketApp("ws://127.0.0.1:10081", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
        self.service.on_open = self.on_open
        self.service.run_forever()
    
    # 向消息服务发送消息
    def write(self, message):
        if self.service is not None and self.service_status:
            self.service.send(json.dumps(message))

    # 打开消息服务
    def on_open(self, ws):
        self._framework.utils.log.info("消息服务连接成功..")
        self.service_status = True
    
    # 收到消息服务发来的信息
    def on_message(self, ws, message):
        message_json = json.loads(message)
        if message_json["command"]:
            # 如果为写入设备类信息
            if message_json["command"] == "write:device:message":
                if self._framework.utils.device.device_connect:
                    self._framework.utils.device.device_write(message_json["body"])
    
    # 消息服务出现错误时
    def on_error(self, ws, error):
        self.service = None
        # 尝试重新连接
        if type(error) == ConnectionRefusedError or type(error)==websocket._exceptions.WebSocketConnectionClosedException:
            # 重启线程
            self._framework.utils.log.warning("消息连接断开，正在尝试重新连接消息服务...")
            self.service_task.reset()

    # 消息服务关闭时
    def on_close(self, ws):
        self.service = None
    
